package com.note7_5;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

public class Question4 {
	/*
	 * 实现文件剪切的功能，输入一个源文件名，和目标文件夹，剪切后文件名保持不变。
	 * 获取源文件的文件名
	 * 复制后将原文件删除
	 * 
	 * 注意：在文件的is或os没有关闭时使用File.delete()方法不能成功，因为文件正在被IO流占用
	 * D:/myeclipse/workpace/com/src/com/stu7_5/question4.txt
	 */
	public void copy(String path,String copyPath){
		InputStream is = null;
		OutputStream os = null;
		File f = null;
		try {
			is = new FileInputStream(path);
			f = new File(path);
			os = new FileOutputStream(copyPath+"/"+f.getName());
			byte[] b = new byte[is.available()];
			while((is.read(b)) > -1){
				os.write(b);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{	//关闭is和os
			if(is != null){
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(os != null){
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(f.delete()){
				System.out.println("操作完成");
			}else{
				System.out.println("操作失败");
			}
		}
	}
	
	public static void main(String[] args) {
		Scanner in =new Scanner(System.in);
		System.out.println("请输入要剪切文件的位置：");
		String path = in.nextLine();
		System.out.println("请输入剪切到的位置：");
		String copyPath = in.nextLine();
		Question4 q = new Question4();
		q.copy(path, copyPath);
	}
	
}
